package com.wing.res.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.device.model.entity.DeviceWorkshop;
import com.wing.device.model.response.DeviceModelVO;
import com.wing.device.model.response.DeviceVO;
import com.wing.device.service.DeviceModelService;
import com.wing.device.service.DeviceService;
import com.wing.device.service.DeviceWorkshopService;
import com.wing.dict.model.entity.DictLabel;
import com.wing.dict.service.DictLabelService;
import com.wing.production.feign.ProductionClient;
import com.wing.production.workOrder.entity.ProProfession;
import com.wing.res.model.request.ResWorkStationUpdateForm;
import com.wing.res.model.response.ResWorkStationSearchVo;
import com.wing.res.service.ResWorkStationService;
import com.wing.user.feign.UserClient;
import com.wing.user.model.request.Role;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.excel.DownExcelUtil;
import com.wing.web.excel.ExcelUtil;
import com.wing.web.excel.WorkStationExcelIn;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 生产研发任务
 * @version 1.1.0
 * @Author hz
 * @Date 2024-09-19 15:36
 **/
@Slf4j
@Validated
@Api(value = "工位管理", tags = "#/res/setting/workStation")
@RestController("resWorkStationController")
@RequestMapping("res/admin/setting/workStation")
public class ResWorkStationController {

    @Resource
    private ResWorkStationService resWorkStationService;
    @Autowired
    private DeviceWorkshopService deviceWorkshopService;
    @Autowired
    private DictLabelService dictLabelService;
    @Autowired
    private DeviceModelService deviceModelService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private ProductionClient productionClient;
    @Autowired
    private UserClient userClient;

    @ApiOperation(value = "查研工位列表", notes = "搜索-工位")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<ResWorkStationSearchVo> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,String name
            ,String code
            ,String professionId
            ,String deviceModelSpuId
            ,String deviceModelSpuIds
            ,String professionIds
            ,String id
            ,Boolean isDeleted
            ,String startCreateTime
            ,String endCreateTime
    ) {
        Page<ResWorkStationSearchVo> pg = new Page<>(page, limit);
        Map<String,Object> map = new HashMap<>();
        map.put("name",name);
        map.put("code",code);
        map.put("id",id);
        map.put("professionId",professionId);
        map.put("deviceModelSpuId",deviceModelSpuId);
        if(StringUtils.isNotEmpty(deviceModelSpuIds)){
            map.put("deviceModelSpuIds", Arrays.asList(deviceModelSpuIds.split(",")));
        }
        if(StringUtils.isNotEmpty(professionIds)){
            map.put("professionIds",Arrays.asList(professionIds.split(",")));
        }
        map.put("isDeleted", isDeleted);
        if (StringUtils.isNotBlank(startCreateTime)) {
            map.put("startCreateTime", startCreateTime);
        }
        if (StringUtils.isNotBlank(endCreateTime)) {
            map.put("endCreateTime", endCreateTime);
        }
        Page<ResWorkStationSearchVo> list =  resWorkStationService.pageList4app(pg, map);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }


    /**
     * 禁用
     * @param id
     * @return
     */
    @ApiOperation(value = "禁用", notes = "禁用")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/cancellation/{id}")
    public JsonResult cancellation(@PathVariable("id") String id) {
        int cancellation = resWorkStationService.cancellation(id);
        if (cancellation > 0) {
            return JsonResult.success("操作成功");
        }else{
            return JsonResult.fail("操作失败");
        }
    }


    /**
     * 启用
     * @param id
     * @return
     */
    @ApiOperation(value = "启用", notes = "启用")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/recover/{id}")
    public JsonResult recover(@PathVariable("id") String id) {
        int cancellation = resWorkStationService.recover(id);
        if (cancellation > 0) {
            return JsonResult.success("操作成功");
        }else{
            return JsonResult.fail("操作失败");
        }
    }

    /**
     * 修改工位信息
     * @param form
     * @return
     */
    @ApiOperation(value = "修改工位信息", notes = "工位-变更")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PutMapping("/updateWorkStationBy")
    public JsonResult updateWorkStationBy(@RequestBody ResWorkStationUpdateForm form) {
        int result = resWorkStationService.updateWorkStationBy(form);
        if (result > 0) {
            if (result == 99){
                return JsonResult.fail("工位编码已存在！");
            }
            return JsonResult.success("操作成功");
        }else{
            return JsonResult.fail("操作失败");
        }
    }


    /**
     * 添加工位信息
     * @param form
     * @return
     */
    @ApiOperation(value = "新增工位信息", notes = "工位-新增")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/addWorkStationBy")
    public JsonResult resWorkStationService(@RequestBody ResWorkStationUpdateForm form) {
        int result = resWorkStationService.addWorkStationBy(form);
        if (result > 0) {
            return JsonResult.success("操作成功");
        }else{
            return JsonResult.fail("操作失败");
        }
    }

    /**
     * 下载excel模板
     */
    @ApiOperation(value = "下载excel模板")
    @GetMapping("/templateDownload")
    public void templateDownload(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String[] headerArr = {"所在车间", "工位性质", "设备型号(设备SPU)", "设备编号(设备SKU)", "责任工种", "责任岗位", "备注"};
        List<String[]> downData = new ArrayList<>();
        List<String> indexArr = new ArrayList<>();
        StringBuffer tempStr = new StringBuffer();
        //车间
        List<DeviceWorkshop> deviceWorkshopList = deviceWorkshopService.getBaseMapper().selectList(new QueryWrapper<>());
        if(CollectionUtil.isNotEmpty(deviceWorkshopList)){
            for (DeviceWorkshop deviceWorkshop : deviceWorkshopList) {
                tempStr.append(deviceWorkshop.getName()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("0");
        }
        //工位性质
        List<DictLabel> dictLabelList = dictLabelService.list(new QueryWrapper<DictLabel>().eq("dict_type", "station_nature_name"));
        if(CollectionUtil.isNotEmpty(dictLabelList)){
            for (DictLabel dictLabel : dictLabelList) {
                tempStr.append(dictLabel.getLabelName()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("1");
        }
        //设备型号(设备SPU)
        List<DeviceModelVO> deviceModelVOList = deviceModelService.list4app(null);
        if(CollectionUtil.isNotEmpty(deviceModelVOList)){
            for (DeviceModelVO deviceModelVO : deviceModelVOList) {
                tempStr.append(deviceModelVO.getName()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("2");
        }
        //设备编号(设备SKU)
        List<DeviceVO> deviceVOList= deviceService.list4app(new HashMap());
        if(CollectionUtil.isNotEmpty(deviceVOList)){
            for (DeviceVO deviceVO : deviceVOList) {
                tempStr.append(deviceVO.getDeviceName()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("3");
        }
        //责任工种
        JsonResult<List<ProProfession>> jsonResult = productionClient.getAllProfession();
        if (jsonResult != null && CollectionUtil.isNotEmpty(jsonResult.getData())) {
            List<ProProfession> proProfessionList = jsonResult.getData();
            for (ProProfession proProfession : proProfessionList) {
                tempStr.append(proProfession.getProfessionName()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("4");
        }
        //责任岗位
        JsonResult<List<Role>> roleData = userClient.getAllRole();
        if (roleData != null && CollectionUtil.isNotEmpty(roleData.getData())) {
            List<Role> roleList = roleData.getData();
            for (Role role : roleList) {
                tempStr.append(role.getName()).append(",");
            }
            tempStr.delete(tempStr.length()-1, tempStr.length());
            downData.add(tempStr.toString().split(","));
            tempStr.delete(0,tempStr.length());
            indexArr.add("5");
        }
        DownExcelUtil.createExcelTemplate(response, request, "工位设置导入模板", Arrays.asList(headerArr), downData, indexArr);

    }

    /**
     * 导入excel
     */
    @ApiOperation(value = "导入excel")
    @PostMapping("/importExcel")
    public JsonResult importExcel(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return JsonResult.fail("导入文件为空！");
        }
        try {
            //获取原始的文件名
            String originalFilename = file.getOriginalFilename();
            String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
            ExcelUtil<WorkStationExcelIn> reader = new ExcelUtil<>();
            InputStream is = file.getInputStream();
            List<WorkStationExcelIn> list = reader.read(is, WorkStationExcelIn.class);
            if (CollectionUtils.isEmpty(list)) {
                return JsonResult.fail("请在表格中添加数据！");
            }
            resWorkStationService.importExcel(list);
        } catch (BusinessException e) {
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.exception("导入文件异常！异常信息:" + e.getMessage());
        }
        return JsonResult.success("导入成功！");
    }
}
